package com.songlanyun.modules.rabbitmq.mq.producer.impl;

import com.alibaba.fastjson.JSON;
import com.songlanyun.common.enums.*;
import com.songlanyun.modules.marketing.groupbuy.entity.GroupBuyTeam;
import com.songlanyun.modules.marketing.groupbuy.entity.GroupBuyTeamMember;
import com.songlanyun.modules.marketing.groupbuy.service.GroupBuyTeamMemberService;
import com.songlanyun.modules.message.model.to.MessageTO;
import com.songlanyun.modules.message.service.SendPrivateMessageMsgService;
import com.songlanyun.modules.order.entity.ChildOrder;
import com.songlanyun.modules.order.entity.Order;
import com.songlanyun.modules.payorder.entity.PayOrder;
import com.songlanyun.modules.payrefund.entity.PayRefundOrder;
import com.songlanyun.modules.rabbitmq.DelayedConstant;
import com.songlanyun.modules.rabbitmq.MqConstant;
import com.songlanyun.modules.rabbitmq.mq.producer.SendOrderOrRightsOrderMsgService;
import com.songlanyun.modules.rabbitmq.service.SendMsgService;
import com.songlanyun.modules.refillorder.service.SaleRefillCardOrderService;
import com.songlanyun.modules.rights.entity.RightsOrder;
import com.songlanyun.modules.rights.service.RightsOrderService;
import com.songlanyun.modules.saleconfig.entity.SaleConfig;
import com.songlanyun.modules.saleconfig.service.SaleConfigService;
import com.songlanyun.modules.ship.entity.OrderPackage;
import com.songlanyun.modules.singlegoods.entity.UnderStockRecordEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service("sendOrderOrRightsOrderMsgService")
public class SendOrderOrRightsOrderMsgImpl implements SendOrderOrRightsOrderMsgService {

    @Autowired
    private SendMsgService sendMsgService;

    @Autowired
    private SaleConfigService saleConfigService;

    @Autowired
    private RightsOrderService rightsOrderService;

    @Autowired
    private GroupBuyTeamMemberService groupBuyTeamMemberService;

    @Autowired
    private SaleRefillCardOrderService saleRefillCardOrderService;

    @Autowired
    private SendPrivateMessageMsgService sendPrivateMessageMsgService;


    /**
     * 支付成功发送消息
     * 发送消息不能写在事物内
     *
     * @param payOrder
     */
    @Override
    public void paySuccessSendMsg(PayOrder payOrder) {
        /**
         * 发送消息不能写在事物内
         */
        switch (payOrder.getOrderType()) {
            case SALE_ORDER:
                payOrder.loadOrders().forEach(order -> {

//                    /**
//                     * 发送支付成功计算商家所得消息--后--再处理消息主要是用来做会员升级----------------------------------------------------------------------
//                     */
//                    if (order.getTotalAmount().compareTo(BigDecimal.ZERO) > 0) {
//                        sendMsgService.send(MqConstant.ComputeShopGainsConstant.COMPUTE_SHOP_GAINS_EXCHANGE, MqConstant.ComputeShopGainsConstant.COMPUTE_SHOP_GAINS_ROUTER
//                                , order.getId().toString());
//                    }

                    /**
                     * 发送自提订单自动备货消息(拼团订单不能自动备货)
                     */
                    if (order.getAutoStockUpLastTime() > 0 && order.getMarketingType() != 2) {

                        int sec = (int) ((order.getAutoStockUpLastTime() - System.currentTimeMillis()) / 1000);
//                        sec = 180;
                        sendMsgService.send(DelayedConstant.OrderAutoStockUpConstant.AUTO_STOCK_UP_DELAYED_EXCHANGE, DelayedConstant.OrderAutoStockUpConstant.AUTO_STOCK_UP_DELAYED_ROUTING
                                , order.getId().toString(), sec);
                    }

                    if (order.getMarketingType() == 2) {
                        GroupBuyTeamMember teamMember = groupBuyTeamMemberService.getByOrderIdAndUserId(order.getId(), order.getUserId());
                        GroupBuyTeam groupBuyTeam = teamMember.loadGroupBuyTeam();

                        //开团成功发送开团后组团过期的延迟消息
                        if (OrderConstant.TeamStatus.CREAT_SUCCESS.equals(groupBuyTeam.getStatus()) && groupBuyTeam.getEndTime() > 0) {
                            int sec = (int) ((groupBuyTeam.getEndTime() - System.currentTimeMillis()) / 1000);
//                            sec = 30;
                            sendMsgService.send(DelayedConstant.AutoExpireTeamConstant.AUTO_EXPIRE_TEAM_DELAYED_EXCHANGE, DelayedConstant.AutoExpireTeamConstant.AUTO_EXPIRE_TEAM_DELAYED_ROUTING
                                    , groupBuyTeam.getId().toString(), sec);
                        }
                    }

                    //发送站内消息
                    sendPaySuccessPriMessage(order);

                });
                break;
            case SERVICE_ORDER:
                payOrder.loadOrders().forEach(order -> {

                    /**
                     * 发送支付成功计算商家所得消息--后--再处理消息主要是用来做会员升级----------------------------------------------------------------------
                     */
//                    sendMsgService.send(MqConstant.ComputeShopGainsConstant.COMPUTE_SHOP_GAINS_EXCHANGE, MqConstant.ComputeShopGainsConstant.COMPUTE_SHOP_GAINS_ROUTER
//                            , order.getId().toString());

                    /**
                     * 如果是服务订单，支付成功之后不发起封单消息
                     * 服务订单不做自动封单
                     * 1、只有服务订单使用完成直接封单，2、维权退款完成才封单
                     * 2、使用完成之后开始自动评价


                     ChildOrder childOrder = order.getChildOrderList(true).get(0);
                     int sec = (int) ((childOrder.getLastEndTime() - System.currentTimeMillis()) / 1000);
                     sendMsgService.send(DelayedConstant.ChildOrderAutoEndConstant.CHILD_ORDER_AUTO_END_DELAYED_EXCHANGE,DelayedConstant.ChildOrderAutoEndConstant.CHILD_ORDER_AUTO_END_DELAYED_ROUTING
                     ,childOrder.getId().toString(),sec);

                     SaleConfig config = saleConfigService.getConfig();
                     //发送自动评价命令============================================

                     if (config.getCommentOpen() && childOrder.getLastCommentTime() > 0) {

                     sec = (int) ((childOrder.getLastCommentTime() - System.currentTimeMillis()) / 1000);
                     sendMsgService.send(DelayedConstant.ChildOrderAutoCommentConstant.CHILD_ORDER_AUTO_COMMENT_DELAYED_EXCHANGE, DelayedConstant.ChildOrderAutoCommentConstant.CHILD_ORDER_AUTO_COMMENT_DELAYED_ROUTING
                     , childOrder.getId().toString(), sec);
                     }
                     **/

                    //发送站内消息
                    sendPaySuccessPriMessage(order);
                });
                break;
        }

    }

    /**
     * 发送支付的站内消息
     *
     * @param order
     */
    private void sendPaySuccessPriMessage(Order order) {

        sendPrivateMessageMsgService.send(new MessageTO(PrivateMessageConstant.MessageType.PAY_MESSAGE,
                PrivateMessageConstant.ModelType.ORDER_PAY_SUCCESS, order.getId()));

    }

    /**
     * 下单成功发送消息
     *
     * @param payOrder
     */
    @Override
    public void createPayOrderSuccessSendMsg(PayOrder payOrder) {
        int sec = (int) ((payOrder.getExpiredPayTime() - System.currentTimeMillis()) / 1000);
        //sec = 30;
        sendMsgService.send(DelayedConstant.OrderDelayedConstant.ORDER_DELAYED_EXCHANGE, DelayedConstant.OrderDelayedConstant.ORDER_DELAYED_ROUTING
                , payOrder.getId().toString(), sec);
    }

    /**
     * 物流订单发货完成发送消息(自动收货)
     *
     * @param orderPackage
     */
    @Override
    public void expressShipSuccessSendMsg(OrderPackage orderPackage) {
        if (orderPackage.getReceiptExpireTime() > 0) {
            int sec = (int) ((orderPackage.getReceiptExpireTime() - System.currentTimeMillis()) / 1000);
            //sec = 180;
            sendMsgService.send(DelayedConstant.OrderAutoReceiptConstant.AUTO_RECEIPT_DELAYED_EXCHANGE, DelayedConstant.OrderAutoReceiptConstant.AUTO_RECEIPT_DELAYED_ROUTING
                    , orderPackage.getId().toString(), sec);
        }
        /**
         * 发送微信订阅消息
         */
//        sendMsgService.send(MqConstant.ShipSuccessSendMessageConstant.SHIP_SUCCESS_SEND_MESSAGE_EXCHANGE, MqConstant.ShipSuccessSendMessageConstant.SHIP_SUCCESS_SEND_MESSAGE_ROUTER
//                , orderPackage.getId().toString());

        /**
         * 发送物流站内消息
         */
        sendLogisticsPriMessage(orderPackage);
    }

    private void sendLogisticsPriMessage(OrderPackage orderPackage) {
        sendPrivateMessageMsgService.send(new MessageTO(PrivateMessageConstant.MessageType.LOGISTICS_MESSAGE,
                PrivateMessageConstant.ModelType.LOGISTICS, orderPackage.getId()));

    }

    /**
     * 自提订单备货完成发送消息(自动收货)
     *
     * @param orderPackage
     */
    @Override
    public void pickupShipSuccessSendMsg(OrderPackage orderPackage) {
        if (orderPackage.getReceiptExpireTime() > 0) {
            int sec = (int) ((orderPackage.getReceiptExpireTime() - System.currentTimeMillis()) / 1000);
//            sec = 180;
            sendMsgService.send(DelayedConstant.OrderAutoPickupConstant.AUTO_PICKUP_DELAYED_EXCHANGE, DelayedConstant.OrderAutoPickupConstant.AUTO_PICKUP_DELAYED_ROUTING
                    , orderPackage.getId().toString(), sec);
        }

//        /**
//         * 发送微信订阅消息
//         */
//        sendMsgService.send(MqConstant.ShipSuccessSendMessageConstant.SHIP_SUCCESS_SEND_MESSAGE_EXCHANGE, MqConstant.ShipSuccessSendMessageConstant.SHIP_SUCCESS_SEND_MESSAGE_ROUTER
//                , orderPackage.getId().toString());
        /**
         * 发送物流站内消息
         */
        sendLogisticsPriMessage(orderPackage);
    }

    /**
     * 会员收货完成发送封装消息
     *
     * @param order
     */
    @Override
    public void receiptSuccessSendMsg(Order order) {
        endSendMsg(order);
    }

    /**
     * 核销自提订单成功发送封消息
     *
     * @param order
     */
    @Override
    public void verificationSuccessSendMsg(Order order) {
        endSendMsg(order);
    }

    /**
     * 核销服务订单全部完成
     * @param childOrder
     */
    @Override
    public void checkServiceOrderCompleteSendMsg(ChildOrder childOrder) {
        SaleConfig config = saleConfigService.getConfig();
        if (config != null) {
            /**
             * 发送自动评价命令============================================
             */
            if (config.getCommentOpen() && childOrder.getLastCommentTime() > 0) {

                int sec = (int) ((childOrder.getLastCommentTime() - System.currentTimeMillis()) / 1000);
//                    sec = 180;
                sendMsgService.send(DelayedConstant.ChildOrderAutoCommentConstant.CHILD_ORDER_AUTO_COMMENT_DELAYED_EXCHANGE, DelayedConstant.ChildOrderAutoCommentConstant.CHILD_ORDER_AUTO_COMMENT_DELAYED_ROUTING
                        , childOrder.getId().toString(), sec);
            }
        }
    }


    /**
     * 会员申请维权发送自动同意的消息
     *
     * @param rightsOrder
     */
    @Override
    public void applyRightsOrderSuccessSendMsg(RightsOrder rightsOrder) {
        if (rightsOrder.getLastAgreeTime() > 0) {
            //维权申请商家过期没处理自动同意
            int sec = (int) ((rightsOrder.getLastAgreeTime() - System.currentTimeMillis()) / 1000);
            //sec = 180;
            sendMsgService.send(DelayedConstant.RightsAutoAgreeConstant.RIGHTS_AUTO_AGREE_DELAYED_EXCHANGE, DelayedConstant.RightsAutoAgreeConstant.RIGHTS_AUTO_AGREE_DELAYED_ROUTING
                    , rightsOrder.getId().toString(), sec);
        }
    }

    /**
     * 商家同意维权后发送维权
     *
     * @param rightsOrder
     */
    @Override
    public void rightsAgreeSendMsg(RightsOrder rightsOrder) {
        if (OrderConstant.RightsType.RETURN.equals(rightsOrder.getRightsType()) && rightsOrder.getLastShipTime() > 0) {
            //发送 商家同意之后，买家过期没有填写物流单，需要自动取消的维权单（退货单）的延迟消息
            int sec = (int) ((rightsOrder.getLastShipTime() - System.currentTimeMillis()) / 1000);
//            sec = 180;
            if(!rightsOrder.getThird()) {
                sendMsgService.send(DelayedConstant.RightsAutoCancelConstant.RIGHTS_AUTO_CANCEL_DELAYED_EXCHANGE, DelayedConstant.RightsAutoCancelConstant.RIGHTS_AUTO_CANCEL_DELAYED_ROUTING
                        , rightsOrder.getId().toString(), sec);
            }
        }

        //发送消息
        sendMsgService.send(MqConstant.BusinessRightsSendMessageConstant.BUSINESS_RIGHTS_SEND_MESSAGE_EXCHANGE, MqConstant.BusinessRightsSendMessageConstant.BUSINESS_RIGHTS_SEND_MESSAGE_ROUTER
                , rightsOrder.getId().toString());
    }

    /**
     * 商家拒绝维权后发送维权
     *
     * @param rightsOrder
     */
    @Override
    public void rightsRefuseSendMsg(RightsOrder rightsOrder) {
        //发送消息
        sendMsgService.send(MqConstant.BusinessRightsSendMessageConstant.BUSINESS_RIGHTS_SEND_MESSAGE_EXCHANGE, MqConstant.BusinessRightsSendMessageConstant.BUSINESS_RIGHTS_SEND_MESSAGE_ROUTER
                , rightsOrder.getId().toString());
    }


    /**
     * 维权退款成功发送微信小程序消息
     *
     * @param payRefundOrder
     */
    @Override
    public void rightsRefundSuccessSendMsg(PayRefundOrder payRefundOrder) {
        // 判断是否退款成功（三方）
        if (payRefundOrder.getRightsRefundStatus().equals(RightsOrderConstant.RightsRefundStatus.SUCCESS)) {
            // 判断是不是消费订单
            if (OrderConstant.OrderType.SALE_ORDER.equals(payRefundOrder.getOrderType())) {
                // 获取 支付退款单id 的退款维权单数据
                RightsOrder rightsOrder = rightsOrderService.loadByPayRefundOrderId(payRefundOrder.getId(), true);
                //发送消息
                sendMsgService.send(MqConstant.BusinessRightsSendMessageConstant.BUSINESS_RIGHTS_SEND_MESSAGE_EXCHANGE, MqConstant.BusinessRightsSendMessageConstant.BUSINESS_RIGHTS_SEND_MESSAGE_ROUTER
                        , rightsOrder.getId().toString());
            }

        }
    }


    /**
     * 会员退货退款发货后，商家收货发送维权
     *
     * @param rightsOrder
     */
    @Override
    public void rightReceiptSendMsg(RightsOrder rightsOrder) {
        //发送消息
        sendMsgService.send(MqConstant.BusinessRightsSendMessageConstant.BUSINESS_RIGHTS_SEND_MESSAGE_EXCHANGE, MqConstant.BusinessRightsSendMessageConstant.BUSINESS_RIGHTS_SEND_MESSAGE_ROUTER
                , rightsOrder.getId().toString());
    }

    /**
     * 会员维权发货
     *
     * @param rightsOrder
     */
    @Override
    public void rightsShipSendMsg(RightsOrder rightsOrder) {
        if (rightsOrder.getLastReceiptTime() > 0) {
            //商家过期没处理收货需要自动收货的维权单（退货单）
            int sec = (int) ((rightsOrder.getLastReceiptTime() - System.currentTimeMillis()) / 1000);
            //sec = 180;
            sendMsgService.send(DelayedConstant.RightsAutoReceiptConstant.RIGHTS_AUTO_RECEIPT_DELAYED_EXCHANGE, DelayedConstant.RightsAutoReceiptConstant.RIGHTS_AUTO_RECEIPT_DELAYED_ROUTING
                    , rightsOrder.getId().toString(), sec);
        }
    }

    private void endSendMsg(Order order) {
        SaleConfig config = saleConfigService.getConfig();
        if (config != null) {
            List<ChildOrder> childOrderList = order.getChildOrderList(true);
            childOrderList.forEach(childOrder -> {
                /**
                 * 发送自动封单命令============================================
                 */
                if (childOrder.getLastEndTime() > 0 && !childOrder.getEnd()) {
                    int sec = (int) ((childOrder.getLastEndTime() - System.currentTimeMillis()) / 1000);
                    //sec = 600;
                    //加了5分种的缓冲
                    sendMsgService.send(DelayedConstant.ChildOrderAutoEndConstant.CHILD_ORDER_AUTO_END_DELAYED_EXCHANGE, DelayedConstant.ChildOrderAutoEndConstant.CHILD_ORDER_AUTO_END_DELAYED_ROUTING
                            , childOrder.getId().toString(), sec);
                }

                /**
                 * 发送自动评价命令============================================
                 */
                if (config.getCommentOpen() && childOrder.getLastCommentTime() > 0) {

                    int sec = (int) ((childOrder.getLastCommentTime() - System.currentTimeMillis()) / 1000);
                    //sec = 600;
                    sendMsgService.send(DelayedConstant.ChildOrderAutoCommentConstant.CHILD_ORDER_AUTO_COMMENT_DELAYED_EXCHANGE, DelayedConstant.ChildOrderAutoCommentConstant.CHILD_ORDER_AUTO_COMMENT_DELAYED_ROUTING
                            , childOrder.getId().toString(), sec);
                }
            });

        }

        /**
         * 发送已收货站内消息
         * TODO  这里有问题
         */
        OrderPackage orderPackage = order.loadOrderPackage();
        if (orderPackage != null) {
            sendPrivateMessageMsgService.send(new MessageTO(PrivateMessageConstant.MessageType.PAY_MESSAGE,
                    PrivateMessageConstant.ModelType.LOGISTICS, orderPackage.getId()));
        }


    }
}

